const MomentService = require('../services/moment.service');
const FileService = require('../services/file.service');
const {PICTURE_PATH, AVATAR_PATH} = require('../constant/path');
const fs = require("fs");
class MomentController{
 async createMoment(ctx,next){
  //获取数据
    const userId =ctx.user.id
    const {content} = ctx.request.body;
  //将数据插入到数据库
    const moment = await MomentService.create(userId,content);
   //返回数据
    ctx.body = {
      code:200,
      data:moment
    }
  }
  async detail(ctx,next) {
    const momentId = ctx.params.momentId;   //获取url中的参数3
    // const moment = await MomentService.detail(id);
    //根据id查询数据
    const moment = await MomentService.detail(momentId);
    ctx.body = {
      code:200,
      data:moment
    }
  }
  //查询所有的动态
  async list(ctx,next){
    const {offset,size} = ctx.request.query;
    const moments = await MomentService.getMomentList(offset,size);
    ctx.body = {
      code:200,
      data:moments
    }
  }
  //更新动态
  async updateMoment(ctx,next){
    const momentId = ctx.params.momentId;
    const {content} = ctx.request.body;
    console.log(content,momentId);

    const moment = await MomentService.update(momentId,content);
    ctx.body = {
      code:200,
      data:{
        content,
        momentId
      }
    }
  }
  //删除动态
  async deleteMoment(ctx,next){
    const momentId = ctx.params.momentId;
    const moment = await MomentService.deleteMoment(momentId);
    ctx.body = {
      code:200,
      data:momentId,
      moment,
    }
  }
  //标签查询
  async createLabel(ctx,next){
   const {momentId} = ctx.params
    const {labels} = ctx;
   for(let label of labels){
     const isExist = await MomentService.hasLabel(momentId, label.id);
     if(!isExist){
       const result = await MomentService.createLabelByMoment(label.id,momentId);
     }
   }
    ctx.body = {
      code:200,
      message:'创建标签成功',
      data:labels,
    }
  }
  //获取文件详情
  async getFileInfo(ctx,next){
    let {filename} = ctx.params;
    const fileInfo = await FileService.getFileInfoByFilename(filename);
    //返回可以展示的图片
    const type =ctx.request.query.type;
    const types = ['small','middle','large'];
    if(types.some(item=>item===type)){
        filename = filename + '-' + type;
      }
    ctx.response.set('content-type', fileInfo.mimetype);
    ctx.body = fs.createReadStream(`${PICTURE_PATH}/${filename}`)
  }
}

module.exports =new MomentController();